package com.mstar.qs.common.log4j;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.apache.log4j.DailyRollingFileAppender;
import org.apache.log4j.Layout;
import org.apache.log4j.Logger;
import org.apache.log4j.spi.LoggingEvent;

import com.morningstar.qs.api.basic.util.DatetimeUtil;
import com.morningstar.qs.api.basic.util.FileUtil;

public class QuoteSpeedDailyRollingFileAppender extends
		DailyRollingFileAppender {

	private int fileSize = -1;

	public QuoteSpeedDailyRollingFileAppender() {
		super();
	}

	public QuoteSpeedDailyRollingFileAppender(Layout layout, String filename,
			String datePattern) throws IOException {

		super(layout, filename, datePattern);

	}

	public QuoteSpeedDailyRollingFileAppender(Layout layout, String filename,
			String datePattern, String fileSize) throws IOException {
		this(layout, filename, datePattern);
		if (fileSize != null) {
			try {
				this.fileSize = Integer.valueOf(fileSize);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}

	@Override
	protected void subAppend(LoggingEvent arg0) {
		super.subAppend(arg0);

		checkFilesize();

	}

	private void checkFilesize() {
		File file = new File(fileName);
		if(!file.exists()) return;
		String pp=file.getAbsolutePath().substring(
				0,
				file.getAbsolutePath().lastIndexOf(
						System.getProperty("file.separator")));
		File[] files=FileUtil.dirListByDescendingDate(new File(pp));
		try {
			limiteFiles(files);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void limiteFiles(File[] files) throws IOException {
		List<File> ff = new ArrayList<File>();
		for (File f: files) {
			if (f.isFile()) {
				String fn = f.getCanonicalPath().substring(
						f.getAbsolutePath().lastIndexOf(
								System.getProperty("file.separator")) + 1);
				if (fn.startsWith(fileName)
						&& f.getName().length() > fileName.length()) {
					ff.add(f);
				}

			}
		}
		Iterator<File> it=ff.iterator();
		int i=0;
		while(it.hasNext()) {
			File df=it.next();
			if(++i> fileSize) {
				it.remove();
				df.delete();
			}
		}

	}

	public int getFileSize() {
		return fileSize;
	}

	public void setFileSize(int fileSize) {
		this.fileSize = fileSize;
	}

	public static class LogerTest {

		static Logger log = LogFactory.retriveLoger("tts");

		public static void main(String... strings) {
			int i = 0;
			while (true) {
				log.info("Test " + (++i));
				try {
					Thread.sleep(5000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				System.out.println("Test: "+i);
			}
		}

	}


}
